package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getName())
                || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.执行后端注册
        AdUser addUser = getOne(Wrappers
                .<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName()));
        if (addUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String dbPwd = addUser.getPassword();
        String password = dto.getPassword();
        String salt = addUser.getSalt();
        //加密规则：密码加盐
        String saltPwd=password+salt;
        String digestPwd = DigestUtils.md5DigestAsHex(saltPwd.getBytes());
        if (!dbPwd.equals(digestPwd)) {
            CustException.cust(AppHttpCodeEnum.ADMIN_USER_NAMEORPWD_ERROR );
        }
        addUser.setLoginTime(new Date());
        updateById(addUser);

        //3 返回结果
        // 生成Token
        Map<String, Object> resultMap = new HashMap<>();
        String token = AppJwtUtil.getToken(addUser.getId().longValue());
        resultMap.put("token", token);

        // 用户信息
        addUser.setPassword(null);
        addUser.setSalt(null);
        resultMap.put("user", addUser);

        return ResponseResult.okResult(resultMap);


    }
}
